package me.bincker.formwork.web.core.config.jackson.filter

import com.fasterxml.jackson.annotation.JsonView
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter
import com.fasterxml.jackson.databind.ser.PropertyWriter
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter
import kotlin.reflect.KClass

/**
 * JsonHideView注解对应的过滤器，通过判断属性中有无JsonView来判断是否序列化
 */
class JsonHideViewPropertyFilter(
        private val hideViewArray: Array<KClass<*>>,
        private val clazz: KClass<*>
) : SimpleBeanPropertyFilter() {
    companion object{
        const val FILTER_NAME = "SystemJsonFilter"
    }

    override fun include(writer: BeanPropertyWriter) : Boolean {
        return writer.type.isTypeOrSubTypeOf(clazz.java) &&
                !(writer.views?.any { view-> hideViewArray.any { view == it.java } } ?: false)
    }

    override fun include(writer: PropertyWriter): Boolean {
        writer.type.isTypeOrSubTypeOf(clazz.java)
        val jsonView = writer.getAnnotation(JsonView::class.java)
        return !(jsonView?.value?.any { hideViewArray.contains(it) } ?: false)
    }
}